package com.bite.book.controller;

import com.bite.book.constant.Constants;
import com.bite.book.model.Result;
import com.bite.book.model.UserInfo;
import com.bite.book.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    //登录接口
    @RequestMapping(value = "/login",produces = "application/json")
    public Result login(String userName, String password, HttpSession session) {
        log.info("用户登录 userName:{},password:{},",userName,password);
        //1.参数校验
        //2.验证账号密码-硬编码 zhangsan 123456
        //3.存session
        if(!StringUtils.hasLength(userName)||!StringUtils.hasLength(password)) {
            return Result.fail("账号密码不能为空");
        }
        //根据用户名查询用户信息，判断密码是否正确
        UserInfo userInfo = userService.queryUserByName(userName);
        if(userInfo==null||userInfo.getId()<0) {
            return Result.fail("用户不存在");
        }
        if(!password.equals(userInfo.getPassword())) {
            return Result.fail("账号或密码错误");
        }
        //存储Session
        userInfo.setPassword("");
        session.setAttribute(Constants.USER_SESSION_KEY,userInfo);
        return Result.success("");
    }


}
